package com.tjl.foodapp;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.LruCache;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.hutool.core.date.DateUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OrderFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OrderFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public OrderFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment OrderFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OrderFragment newInstance(String param1, String param2) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    //页面元素
    ImageView img_food_order;
    TextView tx_foodname_order,tx_price_order;
    EditText et_num_order;
    TextView tx_username_order,tx_address_order,tx_time_order;
    Spinner sp_suggesttime_order;
    TextView tx_sum_order;
    Button btn_confirm_order,btn_cancel_order;
    //上下文
    Context context;
    //请求队列
    RequestQueue queue;
    //食物
    Food food;
    //用户
    User user;
    //子页面管理器
    FragmentManager manager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        img_food_order = view.findViewById(R.id.img_food_order);
        tx_foodname_order = view.findViewById(R.id.tx_foodname_order);
        tx_price_order = view.findViewById(R.id.tx_price_order);
        et_num_order = view.findViewById(R.id.et_num_order);
        tx_username_order = view.findViewById(R.id.tx_username_order);
        tx_address_order = view.findViewById(R.id.tx_address_order);
        tx_time_order = view.findViewById(R.id.tx_time_order);

        sp_suggesttime_order = view.findViewById(R.id.sp_suggesttime_order);
        tx_sum_order = view.findViewById(R.id.tx_sum_order);
        tx_sum_order.setText("");
        btn_confirm_order = view.findViewById(R.id.btn_confirm_order);
        btn_cancel_order = view.findViewById(R.id.btn_cancel_order);
        //上下文
        context = this.getActivity();
        manager = this.getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(context);
        //订单数量文本框事件
//        et_num_order.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                double sum = food.getPrice()*Integer.parseInt(et_num_order.getText().toString());
//                tx_sum_order.setText(sum + "");
//                return true;
//            }
//        });
        et_num_order.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (et_num_order.getText().toString().length() > 0){
                    double sum = food.getPrice()*Integer.parseInt(et_num_order.getText().toString());
                    tx_sum_order.setText(sum + "");
                }
            }
        });
        //获取前一个页面传递过来的参数
        int food_id = this.getArguments().getInt("food_id");
        int shop_id = this.getArguments().getInt("shop_id");
        //获取食物信息
        getJSONObject(Utils.urlBase+"and_getFoodByFoodId.do?id="+food_id,"food",null);
        //获取用户信息
        getJSONObject(Utils.urlBase+"and_getUserByUserId.do?id="+MainActivity.user_id,"user",null);
        //添加按钮的点击事件
        btn_confirm_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Order order = new Order(0,
                        MainActivity.user_id,
                        user.getUsername(),
                        food.getFood_id(),
                        food.getFoodname(),
                        Integer.parseInt(et_num_order.getText().toString()),
                        Double.parseDouble(tx_sum_order.getText().toString()),
                        new Date(),
                        sp_suggesttime_order.getSelectedItem().toString(),
                        null,
                        null);
                String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(order,Order.class);
                JSONObject obj = null;
                try {
                    obj = new JSONObject(s);
                    //把订单写入购物车
                    //判断总购物车是否存在子购物车
                    Set<Integer> allId = MainActivity.cart.keySet();
                    //判断当前店铺id是否在集合中
                    if (allId.contains(shop_id)){
                        Map<Integer, Integer> map = MainActivity.cart.get(shop_id);
                        Integer oldNum = map.get(food_id);
                        String num = et_num_order.getText().toString();
                        int i = Integer.parseInt(num);
                        if (oldNum == null){
                            map.put(food_id, i);
                        }else{
                            map.put(food_id,oldNum + i);
                        }

                    }else{
                        //创建一个子购物车
                        Map<Integer,Integer> map = new HashMap<>();
                        map.put(food_id,Integer.parseInt(et_num_order.getText().toString()));
                        MainActivity.cart.put(shop_id,map);
                    }
                    //将mqp持久化存储
                    SharedPreferences.Editor edit = MainActivity.sp.edit();
                    edit.putString("cart_json_" + MainActivity.user_id,new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(MainActivity.cart));
                    edit.commit();

                    Toast.makeText(getContext(),"已成功添加到购物车中",Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    bundle.putInt("shop_id",shop_id);
                    bundle.putString("prePage","shoplist");
                    changeFragment(new FoodListFragment(),bundle,"foodlist");
                    //getJSONObject(Utils.urlBase+"and_addOrder.do","order",obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //添加取消按钮的点击事件
        btn_cancel_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("shop_id",shop_id);
                bundle.putInt("food_id",food_id);
                bundle.putString("prePage","order");
                changeFragment(new FoodDetailFragment(),bundle,"fooddetail");
            }
        });
        return view;
    }
    public void changeFragment(Fragment fragment,Bundle bundle,String tag){
        //清空子页面栈
        for(int i=0,count = manager.getBackStackEntryCount();i<count;i++){
            manager.popBackStack();
        }
        //创建一个子页面的事务，以便切换子页面
        FragmentTransaction transaction = manager.beginTransaction();
        //设置子页面的初始化参数
        fragment.setArguments(bundle);
        //切换子页面，让子页面显示到主页面的指定位置
        transaction.add(R.id.linear_fragment,fragment);
        //给栈中的子页面一个标签
        transaction.addToBackStack(tag);
        //提交事务
        transaction.commit();
    }
    public void getJSONObject(String url,String type,JSONObject object){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                if(type.equals("food")) {
                    food = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(), Food.class);
                    getImageByURL(Utils.urlBase+"image/"+food.getPic()+".jpg",img_food_order);
                    tx_foodname_order.setText("菜名："+food.getFoodname());
                    tx_price_order.setText("价钱："+food.getPrice()+"元");
                }
                else if(type.equals("user")) {
                    user = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(), User.class);
                    tx_username_order.setText("用户姓名:"+user.getUsername());
                    tx_address_order.setText("配送地址："+user.getAddress());
                    Date date = new Date();
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm a");
                    String s = format.format(date);
                    tx_time_order.setText("下单时间："+s);
                }
                else if(type.equals("order")){
                    String result = "网络连接错误";
                    try {
                        JSONObject obj = new JSONObject(o.toString());
                        result = obj.getString("msg");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(context,result,Toast.LENGTH_LONG).show();
                }

            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,object,listener1,listener2);
        queue.add(request);
    }
    public void getImageByURL(String url,ImageView imageButton){
        int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
        int cachSize = maxMemory/8;
        LruCache<String, Bitmap> lruCache = new LruCache<String,Bitmap>(cachSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return lruCache.get(s);
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {
                lruCache.put(s,bitmap);
            }
        };
        ImageLoader loader = new ImageLoader(queue,imageCache);
        ImageLoader.ImageListener listener
                = ImageLoader.getImageListener(imageButton,
                R.drawable.ic_launcher_background,
                R.drawable.ic_launcher_foreground);
        loader.get(url,listener);
    }
}